/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


var Socket = Class.create({
    websocket: null,
    wsUrl: null,
    initialize: function( _wsUrl) {
        this.wsUrl = _wsUrl;
    },
    onopen: function(event) {
        $(this).fire('XmppWebSocket::open', event);
    },
    onmessage: function(event) {
        $(this).fire('XmppWebSocket::message', event);
    },
    onerror: function(event) {
        $(this).fire('XmppWebSocket::error', event);
    },
    onclose: function(event) {
        $(this).fire('XmppWebSocket::close', event);
    },
    connect: function() {
        this.websocket = new WebSocket(this.wsUrl);
        this.websocket.onopen = function(event) {
            this.onopen(event);
        };
        this.websocket.onmessage = function(event) {
            this.onmessage(event);
        };
        this.websocket.onerror = function(event) {
            this.onerror(event);
        };
        this.websocket.onclose = function(event) {
            this.onclose(event);
        };
    },
    close: function() {
        try {
            this.websocket.close();
        }
        catch(err) {
            console.log('XmppWebSocket::ERROR::' + err);
        }
    },
    send: function(data) {
        try {
            this.websocket.send(data);
        }
        catch(err) {
            console.log('XmppWebSocket::ERROR::' + err);
            return false;
        }
        return true;
    }
});